<HTML>
<HEAD>
    <TITLE> Mqtt-Server </TITLE>
    <meta charset="utf-8">
</HEAD>

<BODY>
<script src="mqttws31.min.js" type="text/javascript"></script>
F12打开控制台
<br>
<br>
<input type="button" value="0. start and subscribe topic testtopic/# " onclick="doStart()">
<br>
<br>
<input type="button" value="1. send message to topic testtopic/1 " onclick="sendMessage()">
<script>
    var hostname = '127.0.0.1',
        port = 9996,
        clientId = 'pc-web',
        timeout = 5,
        keepAlive = 50,
        cleanSession = false,
        ssl = true,
        userName = 'demo',
        password = '8F3B8DE2FDC8BD3D792BE77EAC412010971765E5BDD6C499ADCEE840CE441BDEF17E30684BD95CA708F55022222CC6161D0D23C2DFCB12F8AC998F59E7213393';
    var client;
    //建立客户端实例
    var options;

    function onConnect() {
        console.log("onConnected");
        client.subscribe("testtopic/#");//订阅主题

        //发送消息
        message = new Paho.MQTT.Message("hello");
        message.destinationName = "testtopic/0";
        client.send(message);
    }

    function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
            console.log("onConnectionLost:" + responseObject.errorMessage);
            console.log("连接已断开");
        }
    }

    function onMessageArrived(message) {
        console.log(message.destinationName + "  :收到消息:  " + message.payloadString);
    }

    function doStart() {
        client = new Paho.MQTT.Client(hostname, port, clientId);
        options = {
            invocationContext: {
                host: hostname,
                port: port,
                path: client.path,
                clientId: clientId
            },
            timeout: timeout,
            keepAliveInterval: keepAlive,
            cleanSession: cleanSession,
            useSSL: ssl,
            userName: userName,
            password: password,
            onSuccess: onConnect,
            onFailure: function (e) {
                console.log(e);
            }
        };
        client.onConnectionLost = onConnectionLost;//注册连接断开处理事件
        client.onMessageArrived = onMessageArrived;//注册消息接收处理事件

        client.connect(options);
    }

    var i = 0;

    function sendMessage() {
        var msg = "welcome to mqtt-server :::" + i++;
        message = new Paho.MQTT.Message(msg);
        message.destinationName = "testtopic/" + i;
        client.send(message);
        console.log("发送消息:" + msg);
    }
</script>
</BODY>
</HTML>
